package com.lxw.site.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import java.util.Calendar;
import java.util.Map;

/**
 * @author 梁星武
 * @version 0.0.3
 * @description JwtUtil:Jwt工具类（普通java环境集成,非springboot）
 * @since 2021/3/21 21:12
 */
public class JwtUtil2 {
    private static String SIGNATURE = "321321321QAAW#$#%--2";
    //生成token
    public static String generateJwt(Map<String,Object> payloadMap,Integer expireSeconds){
        Calendar calendar = Calendar.getInstance();
        if (expireSeconds != null){
            calendar.add(Calendar.SECOND,expireSeconds);
        }else{
            calendar.add(Calendar.DATE,7);//默认过期时间为七天
        }
        String token = "";
        JWTCreator.Builder builder = JWT.create();
        //1.头部 默认即可
        //2.payload
        payloadMap.forEach((k,v)->{
            builder.withClaim(k, String.valueOf(v));
        });
        //3.签名
        token = builder.sign(Algorithm.HMAC256(SIGNATURE));

//        String token = JWT.create().withClaim("username","张三")//设置自定义用户名
//        .withClaim("id",123)
//                .withExpiresAt(calendar.getTime())//设置过期时间
//        .sign(Algorithm.HMAC256("2312312321")) ;// 设置签名 保密且复杂
        return token ;
    }

    //令牌验证
    public static boolean verifyToken(String token){
        try {
            //先验证算法
//            JWTVerifier build =JWT.require(Algorithm.HMAC256(SIGNATURE)).build();
//            JWTVerifier build = JWT.require(Algorithm.HMAC256("2312312321")).build();
            JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
//            DecodedJWT verify = build.verify(token);
//            String username = verify.getClaim("username").asString();
//            String username2 = verify.getClaim("username2").asString();
//            int id = verify.getClaim("id").asInt();
//            System.out.println(username);
//            System.out.println(username2);//null，没有就是null.类型不对呢
//            System.out.println(id);//123 asInt .类型必须对应一致。否则都是null
            return true ;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false ;

    }

    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    public static void main(String[] args) {
//        System.out.println(generateJwt());
//        System.out.println(checkJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTYzMzI3MTcsInVzZXJuYW1lIjoi5byg5LiJIn0.AwCnSWWlPruFI84pD2rlH4NxD2xUezPFWMNEoHldGLg"));
//        System.out.println(checkJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ.eyJleHAiOjE2MTYzMzM0MzcsInVzZXJuYW1lIjoi5byg5LiJIn0.XSMSZ2VjOnYDaBlYGGM06cOHMIPDnC2QRrTaILYgPYc"));
//        System.out.println(checkJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTYzMzM0MzcsInVzZXJuYW1lIjoi5byg5LiJIn0.XSMSZ2VjOnYDaBlYGGM06cOHMIPDnC2QRrTaILYgPYc"));
//        System.out.println(checkJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.yJleHAiOjE2MTYzMzM0MzcsInVzZXJuYW1lIjoi5byg5LiJIn0.XSMSZ2VjOnYDaBlYGGM06cOHMIPDnC2QRrTaILYgPYc"));
//        System.out.println(checkJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTYzMzM0MzcsInVzZXJuYW1lIjoi5byg5LiJIn0.XSMSZ2VjOnYDaBlYGGM06cOHMIPDnC2QRrTaILYgPYc"));
//        System.out.println(checkJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTIzLCJleHAiOjE2MTYzNDMzOTUsInVzZXJuYW1lIjoi5byg5LiJIn0.lBL2veD7nuv2fj5LP9UgQzIREmuCgPe3t96BJ4Anf80"));
        //注意:签名的payload一般保存的json字符串，取出来然后json=>map
        //签名的各种异常
        //The Token has expired on Sun Mar 21 21:18:37 CST 2021 -- 过期
        //Last encoded character (before the paddings if any) is a valid base 64 alphabet but not a possible value. Expected the discarded bits to be zero. -- 修改了header和签名
        //The input is not a valid base 64 encoded string -- 修改了payload
        //com.auth0.jwt.exceptions.SignatureVerificationException: The Token's Signature resulted invalid when verified using the Algorithm: HmacSHA256 --签名不一致
    }
}
